package com.label.Service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.label.Dao.RoleMapper;
import com.label.Model.Do.Role;
import com.label.Model.Query.RoleQuery;
import com.label.Service.RoleService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = {Exception.class})
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Resource
    private RoleMapper roleMapper;

    @Override
    public List<Role> getAllRole() {
        return roleMapper.getRoleById(null);
    }

    @Override
    public List<Role> getRoleById(RoleQuery roleQuery) {
        return roleMapper.getRoleById(roleQuery.getId());
    }

    @Override
    public Boolean addRole(RoleQuery roleQuery) {
        if(roleMapper.selectOne(new QueryWrapper<Role>().lambda().eq(Role::getName,roleQuery.getName()))!=null)
            return false;

        Role role= BeanUtil.copyProperties(roleQuery,Role.class,"permissions");
        roleMapper.insert(role);
        if(roleQuery.getPermissions()!=null&&!roleQuery.getPermissions().isEmpty())
            roleMapper.saveRolePermission(String.valueOf(role.getId()),roleQuery.getPermissions().stream().map(String::valueOf).collect(Collectors.toList()));
        return true;
    }

    @Override
    public Boolean delRole(RoleQuery roleQuery) {
        if(roleMapper.getRoleById(roleQuery.getId()).isEmpty())
            return false;
        roleMapper.delRolePermission(String.valueOf(roleQuery.getId()));
        roleMapper.deleteById(roleQuery.getId());
        return true;
    }

    @Override
    public Boolean updateRole(RoleQuery roleQuery) {
        if(roleMapper.getRoleById(roleQuery.getId()).isEmpty())
            return false;
        if(!BeanUtil.isEmpty(roleQuery,"permissions","id")){
            Role role=BeanUtil.copyProperties(roleQuery,Role.class,"permissions");
            roleMapper.updateById(role);
        }
        if(roleQuery.getPermissions()!=null){
            roleMapper.delRolePermission(String.valueOf(roleQuery.getId()));
            if(!roleQuery.getPermissions().isEmpty()){
                roleMapper.saveRolePermission(String.valueOf(roleQuery.getId()), roleQuery.getPermissions().stream().map(String::valueOf).collect(Collectors.toList()));
            }
        }
        return true;
    }

    @Override
    @Cacheable(value = "role",key = "'userId_'+#userId")
    public List<Role> getRoleByUser(Long userId) {
        return roleMapper.getRoleByUser(userId);
    }


}
